package jnpf.service.impl;

import jnpf.model.ragFlow.common.RagFlowApiResult;
import jnpf.model.ragFlow.file.DocumentListRequest;
import jnpf.model.ragFlow.file.FileListResp;
import jnpf.model.themefile.RelationData;
import jnpf.util.UserProvider;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.entity.*;
import jnpf.mapper.ThemeTreeMapper;
import jnpf.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.theme.*;
import jnpf.util.GeneraterSwapUtil;
import jnpf.base.model.ColumnDataModel;
import org.jetbrains.annotations.NotNull;
import org.mortbay.util.ajax.JSON;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;

import jnpf.util.*;

import java.util.*;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSONObject;

/**
 * theme
 * 版本： V3.5
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2025-05-08
 */
@Service
public class ThemeTreeServiceImpl extends ServiceImpl<ThemeTreeMapper, ThemeTreeEntity> implements ThemeTreeService {
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private ThemeService themeService;
    @Autowired
    private ThemeTreeService themeTreeService;
    @Autowired
    private ThemeFileService themeFileService;
    @Autowired
    private FileMangeService fileMangeService;
    @Autowired
    private RagFlowFileService fileService;

    //子表过滤方法
    @Override
    public QueryWrapper<ThemeTreeEntity> getChild(ThemePagination pagination, QueryWrapper<ThemeTreeEntity> themeTreeQueryWrapper) {
        boolean pcPermission = false;
        boolean appPermission = false;
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        String ruleQueryJson = isPc ? ThemeConstant.getColumnData() : ThemeConstant.getAppColumnData();
        ColumnDataModel dataModel = JsonUtil.getJsonToBean(ruleQueryJson, ColumnDataModel.class);
        String ruleJson = isPc ? JsonUtil.getObjectToString(dataModel.getRuleList()) : JsonUtil.getObjectToString(dataModel.getRuleListApp());
        if (isPc) {
        }
        return themeTreeQueryWrapper;
    }

    @NotNull
    @Transactional
    public ActionResult<String> getStringActionResult(List<TreeSaveDTO> treeSaveDTOList, String themeId, String status) {
        try {
            if (!Objects.equals(status, "1") && !Objects.equals(status, "2")) {
                return ActionResult.fail("状态参数异常");
            }
            List<TreeSaveDTO> addList = new ArrayList<>();

            for (TreeSaveDTO dto : treeSaveDTOList) {
                switch (dto.getStatus()) {
                    case "0": // 不处理
                        continue;
                    case "1": // 新增
                        addList.add(dto);
                        break;
                    case "2": // 修改
                        if (StringUtil.isEmpty(dto.getId())) {
                            return ActionResult.fail("修改操作必须提供ID");
                        }
                        ThemeTreeEntity updateEntity = this.getById(dto.getId());
                        if (updateEntity == null) {
                            return ActionResult.fail("要修改的记录不存在");
                        }
                        // 根据当前发布状态处理
                        if ("0".equals(updateEntity.getPublish())) {
                            // 草稿状态,保持草稿状态
                            updateEntity.setName(dto.getLabel());
                            updateEntity.setPublish("0");
                        } else if ("1".equals(updateEntity.getPublish())) {
                            // 已发布状态, 标记为已有编辑
                            updateEntity.setDraft(dto.getLabel());
                            updateEntity.setPublish("20");
                        } else if ("20".equals(updateEntity.getPublish())) {
                            // 已有编辑状态,保持20状态不变
                            updateEntity.setDraft(dto.getLabel());
                        }
                        updateEntity.setThemeid(dto.getThemeId());
                        updateEntity.setPid(dto.getPid());
                        updateEntity.setDes(dto.getDes());
                        updateEntity.setSort(BigDecimal.valueOf(dto.getSort()));
                        this.updateById(updateEntity);
                        break;
                    case "3": // 删除
                        if (StringUtil.isEmpty(dto.getId())) {
                            return ActionResult.fail("删除操作必须提供ID");
                        }
                        // 先查询记录状态
                        ThemeTreeEntity entity = this.getById(dto.getId());
                        if (entity == null) {
                            continue;
//                            return ActionResult.fail("要删除的记录不存在");
                        }
                        // 根据publish值决定操作
                        if ("0".equals(entity.getPublish())) {
                            this.removeById(dto.getId());
                        } else if ("1".equals(entity.getPublish())) {
                            this.update(new LambdaUpdateWrapper<ThemeTreeEntity>().eq(ThemeTreeEntity::getId, dto.getId()).set(ThemeTreeEntity::getPublish, "3"));
                        }
                        break;
                    default:
                        return ActionResult.fail("无效的操作状态: " + dto.getStatus());
                }
            }
            List<ThemeTreeEntity> list = this.lambdaQuery().select(ThemeTreeEntity::getId).likeLeft(ThemeTreeEntity::getId, "new_").list();
            ArrayList<String> ids = new ArrayList<>();
            for (ThemeTreeEntity themeTreeEntity : list) {
                ids.add(themeTreeEntity.getId());
            }
            ArrayList<ThemeTreeEntity> themeTreeEntities = new ArrayList<>();
            for (TreeSaveDTO dto : addList) {
                String id = dto.getId();
                if (!ids.contains(id)) {
                    ThemeTreeEntity newEntity = new ThemeTreeEntity();
                    newEntity.setId(dto.getId());
                    newEntity.setName(dto.getLabel());
                    newEntity.setThemeid(dto.getThemeId());
                    newEntity.setPid(dto.getPid());
                    newEntity.setDes(dto.getDes());
                    newEntity.setPublish("0");
                    newEntity.setSort(BigDecimal.valueOf(dto.getSort()));
                    themeTreeEntities.add(newEntity);
                }
            }
            if (!themeTreeEntities.isEmpty()) {
                this.saveBatch(themeTreeEntities);
            }

            //更新这个节点的状态
            ThemeEntity theme = themeService.getById(themeId);
            theme.setUpdatetime(new Date());
            UserInfo userInfo = userProvider.get();
            theme.setUpdateuser(userInfo.getUserId());
            if (status.equals("1")) {
                theme.setThemestatus("0");
            } else if (status.equals("2")) {
                theme.setThemestatus("2");
            }
            themeService.updateById(theme);


            //若为2，则保存为新版本
            if (status.equals("2")) {

                //设置其他不为主版本，停用
                themeService.update(null, new LambdaUpdateWrapper<ThemeEntity>().eq(ThemeEntity::getFirstversion, theme.getFirstversion()).set(ThemeEntity::getIsmain, 0).set(ThemeEntity::getThemestatus, "2"));

                // 获取当前日期部分
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
                String datePart = dateFormat.format(new Date());

                // 查询最新版本号
                ThemeEntity latestVersion = themeService.lambdaQuery().eq(ThemeEntity::getId, themeId).orderByDesc(ThemeEntity::getVersion).last("LIMIT 1").one();

                // 生成新版本号
                int sequenceNumber = 1;
                if (latestVersion != null && latestVersion.getVersion() != null) {
                    String[] parts = latestVersion.getVersion().split("_");
                    if (parts.length == 2 && parts[0].equals(datePart)) {
                        sequenceNumber = Integer.parseInt(parts[1]) + 1;
                    }
                }
                String newVersionId = datePart + "_" + sequenceNumber;

                // 处理主题名称，添加版本号信息
                String originalName = theme.getThemename();
                String versionSuffix = "(" + newVersionId + ")";

                // 检查是否已包含版本号
                if (originalName.contains("(") && originalName.contains(")")) {
                    // 如果已有版本号，则更新版本号部分
                    originalName = originalName.replaceAll("\\(.*?\\)", versionSuffix);
                } else {
                    // 如果没有版本号，则添加版本号
                    originalName = originalName + versionSuffix;
                }
//                theme.setThemename(originalName);

                String newId = "";
                //若没有上一版本id,则为初始版本，直接将这个版本设置为主版本
                if (StringUtil.isEmpty(theme.getLastversion())) {
                    theme.setVersion(newVersionId);
                    theme.setLastversion(themeId);
                    theme.setIsmain(1);
                    theme.setThemestatus("1");
                    themeService.updateById(theme);
                    themeTreeService.update(new LambdaUpdateWrapper<ThemeTreeEntity>().eq(ThemeTreeEntity::getThemeid, themeId).set(ThemeTreeEntity::getPublish, "1"));
                } else {
                    newId = RandomUtil.uuId();
                    theme.setVersion(newVersionId);
                    theme.setLastversion(themeId);
                    theme.setCreatetime(new Date());
                    theme.setIsmain(1);
                    theme.setThemestatus("1");
                    theme.setId(newId);
                    themeService.create(theme);
                    // 创建ID映射表用于新旧节点对应关系
                    Map<String, String> idMapping = new HashMap<>();
                    List<ThemeTreeEntity> newVersionList = themeTreeService.lambdaQuery().eq(ThemeTreeEntity::getThemeid, themeId).list();
                    List<ThemeTreeEntity> newVersionEntities = new ArrayList<>();
                    List<ThemeTreeEntity> entitiesToRecover = new ArrayList<>();

                    // 第一遍遍历：生成所有新ID并建立映射关系
                    for (ThemeTreeEntity entity : newVersionList) {
                        // 跳过已有删除状态的记录
                        if ("3".equals(entity.getPublish())) {
                            entitiesToRecover.add(entity);
                            continue;
                        }
                        String newSonId = RandomUtil.uuId();
                        idMapping.put(entity.getId(), newSonId);
                    }

                    // 第二遍遍历：创建实体并建立正确的父子关系
                    for (ThemeTreeEntity entity : newVersionList) {
                        // 跳过已有删除状态的记录
                        if ("3".equals(entity.getPublish())) {
                            continue;
                        }
                        ThemeTreeEntity newEntity = new ThemeTreeEntity();
                        String newSonId = idMapping.get(entity.getId());
                        newEntity.setId(newSonId);
                        newEntity.setThemeid(newId);
                        // 更新PID为映射后的新ID（如果原PID存在映射）
                        String originalPid = entity.getPid();
                        newEntity.setPid(idMapping.getOrDefault(originalPid, originalPid));
                        // 使用draft作为新版本的name（如果有draft值）
                        newEntity.setName(StringUtil.isNotEmpty(entity.getDraft()) ? entity.getDraft() : entity.getName());
                        newEntity.setDes(entity.getDes());
                        newEntity.setSort(entity.getSort());
                        newEntity.setPublish("1");
                        newVersionEntities.add(newEntity);
                    }
                    if (!newVersionEntities.isEmpty()) {
                        this.saveBatch(newVersionEntities);
                    }

                    // 复原已有编辑状态的记录
                    this.update(new LambdaUpdateWrapper<ThemeTreeEntity>().eq(ThemeTreeEntity::getThemeid, themeId).eq(ThemeTreeEntity::getPublish, "20").set(ThemeTreeEntity::getDraft, null).set(ThemeTreeEntity::getPublish, "1"));

                    // 复原已有删除状态的记录
                    this.update(new LambdaUpdateWrapper<ThemeTreeEntity>().eq(ThemeTreeEntity::getThemeid, themeId).eq(ThemeTreeEntity::getPublish, "3").set(ThemeTreeEntity::getPublish, "1"));


                    // 删除旧版本的草稿信息
                    this.remove(new QueryWrapper<ThemeTreeEntity>().eq("themeid", themeId).eq("publish", "0"));

                    // 处理theme_file数据,版本变更的时候，将themeid和nodeid也创建新版本
                    List<ThemeFileEntity> oldThemeFiles = themeFileService.lambdaQuery().eq(ThemeFileEntity::getThemeid, themeId).list();

                    List<ThemeFileEntity> newThemeFiles = new ArrayList<>();
                    for (ThemeFileEntity oldFile : oldThemeFiles) {
                        ThemeFileEntity newFile = new ThemeFileEntity();
                        newFile.setId(RandomUtil.uuId());
                        newFile.setFileid(oldFile.getFileid());
                        newFile.setThemeid(newId); // 使用新主题ID
                        newFile.setNodeid(idMapping.getOrDefault(oldFile.getNodeid(), oldFile.getNodeid())); // 使用映射后的节点ID
                        newFile.setCreatetime(new Date());
                        newFile.setCreateuser(userProvider.get().getUserId());
                        newFile.setDatasetid(oldFile.getDatasetid());
                        newFile.setRagfileid(oldFile.getRagfileid());
                        newFile.setFlowId(oldFile.getFlowId());
                        newThemeFiles.add(newFile);
                    }

                    if (!newThemeFiles.isEmpty()) {
                        themeFileService.saveBatch(newThemeFiles);
                    }
                }
            }
            return ActionResult.success("批量操作成功");
        } catch (Exception e) {
            log.error("批量操作失败", e);
            return ActionResult.fail("批量操作失败: " + e.getMessage());
        }
    }

    @Override
    public RelationData getTreeByThemeIdAndNodeId(String themeid, String nodeid) throws Exception {
        RelationData relationData = new RelationData();

        // 1. 获取当前节点信息
        ThemeTreeEntity currentNode = this.getById(nodeid);
        if (currentNode == null) {
            return null;
        }

        // 2. 获取父节点信息
        String pid = currentNode.getPid();
        ThemeTreeEntity pNode = this.getById(pid);
        // 没有父节点，则查询pid为0的和这些pid0的子节点
        if (pNode == null) {
            relationData.setId("-1");
            relationData.setName("-1");
            relationData.setPid("-1");
            relationData.setType("0");
            relationData.setFileType("1");
            List<ThemeTreeEntity> list1 = this.lambdaQuery().eq(ThemeTreeEntity::getPid, "0").eq(ThemeTreeEntity::getThemeid, themeid).list();
            List<RelationData> child1 = new ArrayList<>();
            for (ThemeTreeEntity theme1 : list1) {
                RelationData relationData1 = new RelationData();
                relationData1.setId(theme1.getId());
                relationData1.setName(theme1.getName());
                relationData1.setPid(theme1.getPid());
                relationData1.setType("1");
                relationData1.setFileType("1");
                List<RelationData> child2 = new ArrayList<>();

                // 原有逻辑：查询ThemeTree的下层节点（文件节点）
                List<ThemeTreeEntity> list2 = this.lambdaQuery().eq(ThemeTreeEntity::getPid, theme1.getId()).list();
                for (ThemeTreeEntity theme2 : list2) {
                    RelationData relationData2 = new RelationData();
                    relationData2.setId(theme2.getId());
                    relationData2.setName(theme2.getName());
                    relationData2.setPid(theme2.getPid());
                    relationData2.setType("1");
                    relationData2.setFileType("1");
                    List<RelationData> child3 = new ArrayList<>();  // 下层节点的子文件列表

                    // 查询下层节点（theme2）的关联文件（来自theme_file和file_mange）
                    List<ThemeFileEntity> themeFiles2 = themeFileService.lambdaQuery()
                            .eq(ThemeFileEntity::getNodeid, theme2.getId())  // 关联下层节点ID
                            .list();
                    for (ThemeFileEntity themeFile2 : themeFiles2) {
                        FileMangeEntity fileMange2 = fileMangeService.lambdaQuery()
                                .eq(FileMangeEntity::getId, themeFile2.getFileid())
                                .one();
                        if (fileMange2 != null) {
                            RelationData fileRelation2 = new RelationData();
                            fileRelation2.setId(fileMange2.getId());
                            fileRelation2.setName(fileMange2.getName());
                            fileRelation2.setPid(theme2.getId());  // 父节点为下层节点ID
                            fileRelation2.setType("2");
                            fileRelation2.setFileType("2");
                            fileRelation2.setRagFileId(fileMange2.getRagfileid());
                            fileRelation2.setDatasetId(fileMange2.getDatasetid());
                            child3.add(fileRelation2);  // 添加到下层节点的子列表
                        }
                    }

                    relationData2.setChildren(child3);  // 下层节点的子文件列表
                    child2.add(relationData2);  // 将下层节点（含子文件）添加到同层文件夹的子列表
                }

                // 查询当前同层文件夹节点（theme1）的关联文件
                List<ThemeFileEntity> themeFiles = themeFileService.lambdaQuery()
                        .eq(ThemeFileEntity::getNodeid, theme1.getId())
                        .list();
                for (ThemeFileEntity themeFile : themeFiles) {
                    FileMangeEntity fileMange = fileMangeService.lambdaQuery()
                            .eq(FileMangeEntity::getId, themeFile.getFileid())
                            .one();
                    if (fileMange != null) {
                        RelationData fileRelation = new RelationData();
                        fileRelation.setId(fileMange.getId());
                        fileRelation.setName(fileMange.getName());
                        fileRelation.setPid(theme1.getId());
                        fileRelation.setType("2");
                        fileRelation.setFileType("2");
                        fileRelation.setRagFileId(fileMange.getRagfileid());
                        fileRelation.setDatasetId(fileMange.getDatasetid());

                        child2.add(fileRelation);
                    }
                }

                relationData1.setChildren(child2);
                child1.add(relationData1);
            }
            relationData.setChildren(child1);
        } else {
            // 修复：查询父节点本身关联的文件
            relationData.setId(pNode.getId());
            relationData.setName(pNode.getName());
            relationData.setPid(pNode.getPid());
            relationData.setType("0");
            relationData.setFileType("1");
            List<RelationData> pNodeChildren = new ArrayList<>();

            // 查询父节点关联的文件
            List<ThemeFileEntity> pNodeThemeFiles = themeFileService.lambdaQuery()
                    .eq(ThemeFileEntity::getNodeid, pNode.getId())
                    .list();
            for (ThemeFileEntity themeFile : pNodeThemeFiles) {
                FileMangeEntity fileMange = fileMangeService.lambdaQuery()
                        .eq(FileMangeEntity::getId, themeFile.getFileid())
                        .one();
                if (fileMange != null) {
                    RelationData fileRelation = new RelationData();
                    fileRelation.setId(fileMange.getId());
                    fileRelation.setName(fileMange.getName());
                    fileRelation.setPid(pNode.getId());
                    fileRelation.setType("2");
                    fileRelation.setFileType("2");
                    fileRelation.setRagFileId(fileMange.getRagfileid());
                    fileRelation.setDatasetId(fileMange.getDatasetid());
                    pNodeChildren.add(fileRelation);
                }
            }

            // 3. 通过父节点找到当前同层节点的信息（文件夹节点）
            List<ThemeTreeEntity> list1 = this.lambdaQuery().eq(ThemeTreeEntity::getPid, pNode.getId()).list();
            List<RelationData> child1 = new ArrayList<>();
            for (ThemeTreeEntity theme1 : list1) {
                RelationData relationData1 = new RelationData();
                relationData1.setId(theme1.getId());
                relationData1.setName(theme1.getName());
                relationData1.setPid(theme1.getPid());
                relationData1.setType("1");
                relationData1.setFileType("1");
                List<RelationData> child2 = new ArrayList<>();

                // 原有逻辑：查询ThemeTree的下层节点（文件节点）
                List<ThemeTreeEntity> list2 = this.lambdaQuery().eq(ThemeTreeEntity::getPid, theme1.getId()).list();
                for (ThemeTreeEntity theme2 : list2) {
                    RelationData relationData2 = new RelationData();
                    relationData2.setId(theme2.getId());
                    relationData2.setName(theme2.getName());
                    relationData2.setPid(theme2.getPid());
                    relationData2.setType("1");
                    relationData2.setFileType("1");
                    List<RelationData> child3 = new ArrayList<>();  // 下层节点的子文件列表

                    // 修复：查询下层节点的关联文件（与pNode==null分支一致）
                    List<ThemeFileEntity> themeFiles2 = themeFileService.lambdaQuery()
                            .eq(ThemeFileEntity::getNodeid, theme2.getId())
                            .list();
                    for (ThemeFileEntity themeFile2 : themeFiles2) {
                        FileMangeEntity fileMange2 = fileMangeService.lambdaQuery()
                                .eq(FileMangeEntity::getId, themeFile2.getFileid())
                                .one();
                        if (fileMange2 != null) {
                            RelationData fileRelation2 = new RelationData();
                            fileRelation2.setId(fileMange2.getId());
                            fileRelation2.setName(fileMange2.getName());
                            fileRelation2.setPid(theme2.getId());
                            fileRelation2.setType("2");
                            fileRelation2.setFileType("2");
                            fileRelation2.setRagFileId(fileMange2.getRagfileid());
                            fileRelation2.setDatasetId(fileMange2.getDatasetid());
                            child3.add(fileRelation2);
                        }
                    }

                    relationData2.setChildren(child3);
                    child2.add(relationData2);
                }

                // 查询theme_file和file_mange关联的文件数据
                List<ThemeFileEntity> themeFiles = themeFileService.lambdaQuery()
                        .eq(ThemeFileEntity::getNodeid, theme1.getId())
                        .list();
                for (ThemeFileEntity themeFile : themeFiles) {
                    FileMangeEntity fileMange = fileMangeService.lambdaQuery()
                            .eq(FileMangeEntity::getId, themeFile.getFileid())
                            .one();
                    if (fileMange != null) {
                        RelationData fileRelation = new RelationData();
                        fileRelation.setId(fileMange.getId());
                        fileRelation.setName(fileMange.getName());
                        fileRelation.setPid(theme1.getId());
                        fileRelation.setType("2");
                        fileRelation.setFileType("2");
                        fileRelation.setRagFileId(fileMange.getRagfileid());
                        fileRelation.setDatasetId(fileMange.getDatasetid());
                        child2.add(fileRelation);
                    }
                }

                relationData1.setChildren(child2);
                child1.add(relationData1);
            }

            // 将父节点文件和同层节点合并
            pNodeChildren.addAll(child1);
            relationData.setChildren(pNodeChildren);
        }


        //将文件放到目录后面
        adjustNodeOrder(relationData.getChildren());

        return relationData;
    }


    private void adjustNodeOrder(List<RelationData> children) {
        if (children == null || children.isEmpty()) {
            return;
        }
        // 分离fileType为1和2的节点
        List<RelationData> type1Nodes = new ArrayList<>();
        List<RelationData> type2Nodes = new ArrayList<>();
        for (RelationData node : children) {
            if ("1".equals(node.getFileType())) {
                type1Nodes.add(node);
                // 递归处理子节点
                adjustNodeOrder(node.getChildren());
            } else if ("2".equals(node.getFileType())) {
                type2Nodes.add(node);
            }
        }
        // 清空原列表，按顺序添加type1和type2节点
        children.clear();
        children.addAll(type1Nodes);
        children.addAll(type2Nodes);
    }

}
